package edu.sctu.zhu.controller;

import com.google.gson.Gson;
import edu.sctu.zhu.bean.*;
import edu.sctu.zhu.bean.Collection;
import edu.sctu.zhu.config.SystemConfig;
import edu.sctu.zhu.dao.*;
import edu.sctu.zhu.weixing.WeixingVerify;
import edu.sctu.zhu.util.HttpClientUtil;
import edu.sctu.zhu.weixing.bean.Openid;
import edu.sctu.zhu.weixing.bean.WeixingUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhu on 2015/10/31.
 */
@RestController
public class ZhuController {

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private GoodsClassfyDao goodsClassfyDao;

    @Autowired
    private TGoodsClassDao tGoodsClassDao;

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private OrderGoodsDao orderGoodsDao;

    @Autowired
    private WorkorderDao workorderDao;

    @Autowired
    private FansDao fansDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private GoodsImageDao goodsImageDao;

    @Autowired
    private CollectionDao collectionDao;

    @Autowired
    private AddressesDao addressesDao;

    @Autowired
    private MyIndexDao myIndexDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AuthoritiesDao authoritiesDao;

    Gson gson = new Gson();

    @RequestMapping(value = "/goods/collection/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String collection(HttpSession httpSession, @PathVariable Long id) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            Fans fans = (Fans) httpSession.getAttribute("weixin");
            Collection collection = collectionDao.findByGoodsAndFans(id, fans.getId());
            if (collection == null) {
                collectionDao.insertCollection(id, fans.getId());
                jsonStatus.status = 2;
                jsonStatus.text = "yes";
            } else {
                collectionDao.delete(collection);
                jsonStatus.status = 0;
                jsonStatus.text = "not";
            }

        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = "fail";
        }
        return gson.toJson(jsonStatus);
    }

    @RequestMapping(value = "/collection", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String mycollection(HttpSession httpSession) {
        JsonListBean<Goods> jsonListBean = new JsonListBean();
        try {
            Fans fans = (Fans) httpSession.getAttribute("weixin");
            jsonListBean.list = goodsDao.findCollection(fans.getId());
            jsonListBean.status = 0;
            jsonListBean.text = "successful";
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
        }
        return gson.toJson(jsonListBean);
    }

    @RequestMapping(value = "/goods/isCollection/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String isCollection(HttpSession httpSession, @PathVariable Long id) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            Fans fans = (Fans) httpSession.getAttribute("weixin");
            Collection collection = collectionDao.findByGoodsAndFans(id, fans.getId());
            if (collection == null) {
                jsonStatus.status = 0;
                jsonStatus.text = "not";
            } else {
                jsonStatus.status = 2;
                jsonStatus.text = "yes";
            }

        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = "fail";
        }


        return gson.toJson(jsonStatus);

    }

    /**
     * @param request
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String UploadRturb(ServletRequest request) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String shopName = request.getParameter("shopname");
            String phone = request.getParameter("phone");

            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            String nowData = simpleDateFormat.format(date);
            Users users = new Users();
            users.setPass(false);
            users.setUsername(username);
            users.setPassword(password);
            users.setShopName(shopName);
            users.setRegTime(nowData);
            users.setPhone(phone);
            usersDao.save(users);
            Long usersId = usersDao.findIdByUsername(username);

            if (request instanceof MultipartHttpServletRequest) {

                Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();

                Image image;

                for (MultipartFile multipartFile : fileMap.values()) {

                    image = getUploadedFileInfo(multipartFile);

                    image.setImageUser("sellerLogo");
                    image.setParent_id(usersId);
                    imageDao.save(image);

                    saveFileToLocalDisk(multipartFile, image.getImageName());
                }


            }
        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = "fail";
            return gson.toJson(jsonStatus);
        }

        jsonStatus.status = 0;
        jsonStatus.text = "successful";
        return gson.toJson(jsonStatus);

    }


    @RequestMapping(value = "/zhu/shelves", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String shelvesRturb(ServletRequest request)  throws IOException {
        JsonStatus jsonStatus = new JsonStatus();

        Long goodsId = Long.getLong("0");
        try {

            if (request instanceof MultipartHttpServletRequest) {

                UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                        .getAuthentication()

                        .getPrincipal();
                String myId = request.getParameter("uid");
                if (myId.equals("0")){


                Goods goods = new Goods();
                GoodsClassfy goodsClassfy = new GoodsClassfy();

                goods.setType(Integer.decode(request.getParameter("type")));
                goods.setName(request.getParameter("goods_name"));
                goods.setPrice(Long.decode(request.getParameter("price")));
                goods.setGoods_number(Long.decode(request.getParameter("goods_number")));

                goods.setCategory(categoryDao.findByCategoryId(Long.decode(request.getParameter("categoryId"))));
                goods.setDescri(request.getParameter("descri"));

                goods.setUsers(usersDao.findByUsername(userDetails.getUsername()));

                goods.setIs_hot(true);

                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String nowData = simpleDateFormat.format(date);
                goods.setAdd_time(nowData);
                String goodsNumber = nowData + userDetails.getUsername() + getRandom();
                goods.setNumber(goodsNumber);

                goodsDao.save(goods);
                Goods newGoods = goodsDao.findByNuber(goodsNumber);
                goodsId = newGoods.getId();
                Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();

                Image image;
                int flag = 0;
                for (MultipartFile multipartFile : fileMap.values()) {
                    flag++;
                    String asdf = request.getParameter("name");
                    image = getUploadedFileInfo(multipartFile);

                    if (asdf.contains("index")){
                        image.setImageUser("goodsIndex");
                    }else if (asdf.contains("describe")){
                        image.setImageUser("goodsDescribe");
                    }else if (asdf.contains("galley")){
                        image.setImageUser("goodsGalley");
                    }
                    image.setParent_id(newGoods.getId());
                    imageDao.save(image);
                    saveFileToLocalDisk(multipartFile, image.getImageName());
                }

//                goodsClassfy.setGoods(newGoods);
                goodsDao.save(newGoods);
//                goodsClassfy.setValue(request.getParameter("classDetile"));
//                goodsClassfy.settGoodsClass(tGoodsClassDao.findOne(Long.decode(request.getParameter("goodsClass"))));
//                goodsClassfyDao.save(goodsClassfy);
                }else {
                    goodsId = Long.valueOf(myId);
                    Goods myGoods = goodsDao.findOne(Long.valueOf(myId));
                    Image image;
                    int flag = 0;
                    Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
                    for (MultipartFile multipartFile : fileMap.values()) {
                        flag++;
                        String asdf = request.getParameter("name");
                        image = getUploadedFileInfo(multipartFile);
                            if (asdf.contains("index")){
                                image.setImageUser("goodsIndex");
                            }else if (asdf.contains("describe")){
                                image.setImageUser("goodsDescribe");
                            }else if (asdf.contains("galley")){
                                image.setImageUser("goodsGalley");
                        }
                        myGoods.setIndex_url(image.getUrl());
                        image.setParent_id(myGoods.getId());
                        imageDao.save(image);
                        saveFileToLocalDisk(multipartFile, image.getImageName());
                    }
                }
            }
        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = String.valueOf(goodsId);
            return  gson.toJson(jsonStatus);
        }
        jsonStatus.status = 0;
        jsonStatus.text = String.valueOf(goodsId);
        return gson.toJson(jsonStatus);
    }

    /**
     * type 0为所有，1为上架，2为未上架
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/goods/seller/{type}/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSellerGood(@PathVariable Long id, @PathVariable Long type) {
        JsonListBean<Goods> jsonListBean = new JsonListBean<Goods>();

        List<Goods> list;
        try {
            if (type == 1) {
                list = goodsDao.findBySellerAndIsShelves(id, true);
            } else if (type == 2) {
                list = goodsDao.findBySellerAndIsShelves(id, false);
            } else {
                list = goodsDao.findBySeller(id);
            }

            jsonListBean.list = list;
            jsonListBean.status = 0;
            jsonListBean.text = "successful";


            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
            return gson.toJson(jsonListBean);
        }


    }

    @RequestMapping(value = "/goods/detail/goods/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getDetailGoods(@PathVariable Long id) {
        JsonBean<Goods> jsonBean = new JsonBean<>();
        try {
            Goods goods = goodsDao.findOne(id);
            jsonBean.bean = goods;
            jsonBean.status = 0;
            jsonBean.text = "successful";
            return gson.toJson(jsonBean);
        } catch (Exception e) {
            jsonBean.status = 1;
            jsonBean.text = "fail";
            return gson.toJson(jsonBean);
        }

    }

    @RequestMapping(value = "/goods/detail/image/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getDetailImage(@PathVariable Long id) {
        JsonListBean<Image> jsonListBean = new JsonListBean<Image>();

        try {
            List<Image> list = imageDao.findByparentId(id);
            jsonListBean.list = list;
            jsonListBean.status = 0;
            jsonListBean.text = "successful";
            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
            return gson.toJson(jsonListBean);
        }

    }

    @RequestMapping(value = "/category", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSellerGood() {
        JsonListBean<Category> jsonListBean = new JsonListBean<Category>();

        try {
            jsonListBean.list = (List<Category>) categoryDao.findAll();
            jsonListBean.status = 0;
            jsonListBean.text = "successful";


            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
            return gson.toJson(jsonListBean);
        }


    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/category/child/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSellerGood(@PathVariable Long id) {
        JsonListBean<Category> jsonListBean = new JsonListBean<Category>();
        try {
            jsonListBean.list = categoryDao.findCategoryChild(id);
            jsonListBean.status = 0;
            jsonListBean.text = "successful";
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
        }

        return gson.toJson(jsonListBean);
    }



    /**
     * 查找当前id下的叶子分类
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/category/leaf/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String sadsad(@PathVariable Long id) {
        JsonListBean<Goods> jsonListBean = new JsonListBean<Goods>();
        boolean flag = true;
        try {


            List<Long> resultList = new ArrayList<Long>();
            Category category = categoryDao.findOne(id);
            if (category.getCount() != 0) {
                List<Category> list = categoryDao.findCategoryChild(category.getId());
                while (flag) {
                    List<Category> tempList = new ArrayList<>();
                    tempList.addAll(list);
                    for (Category myid : tempList) {
                        list.remove(myid);
                        if (myid.getCount() == 0) {
                            resultList.add(myid.getId());
                        } else {
                            List<Category> childList = categoryDao.findCategoryChild(myid.getId());
                            list.addAll(childList);
                        }
                    }

                    if (list.size() == 0)
                        flag = false;
                }
            } else {
                resultList.add(id);
            }
            List<Goods> goodsList = new ArrayList<>();
            for (Long categoryId : resultList) {

                goodsList.addAll(goodsDao.findCategoryGoods(categoryId));
            }
            jsonListBean.list = goodsList;
            jsonListBean.status = 0;
            jsonListBean.text = "successful";
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
        }
        return gson.toJson(jsonListBean);
    }

    @RequestMapping(value = "/goods/category/{type}/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getCategoryGood(@PathVariable Long id, @PathVariable Long type) {
        JsonListBean<Goods> jsonListBean = new JsonListBean<Goods>();

        List<Goods> list;
        try {
            if (type == 1) {
                list = goodsDao.findByCategoryAndIshelves(id, true);
            } else if (type == 2) {
                list = goodsDao.findByCategoryAndIshelves(id, false);
            } else {
                System.out.println();
                list = goodsDao.findByCategory(id);
            }

            jsonListBean.list = list;
            jsonListBean.status = 0;
            jsonListBean.text = "successful";


            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
            return gson.toJson(jsonListBean);
        }


    }

    @RequestMapping(value = "/goods/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getGoods(@PathVariable Long id) {
        JsonBean<Goods> jsonBean = new JsonBean<Goods>();
        try {
            jsonBean.bean = goodsDao.findOne(id);
            jsonBean.status = 0;
            jsonBean.text = "successful";
        } catch (Exception e) {
            jsonBean.status = 1;
            jsonBean.text = "fail";
        }
        return gson.toJson(jsonBean);

    }

    @RequestMapping(value = "/fans/address/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String addaddress(ServletRequest request, HttpSession session) {
        JsonStatus jsonStatus = new JsonStatus();
        Addresses addresses = new Addresses();
        try {
            List<Addresses> addressesList = addressesDao.findByFans(((Fans) session.getAttribute("weixin")).getId());
            String prov = request.getParameter("prov");
            String city = request.getParameter("city");
            String county = request.getParameter("county");
            addresses.setFansAddress(prov + city + county + request.getParameter("address"));
            addresses.setPhone(request.getParameter("phone"));
            addresses.setFansName(request.getParameter("name"));
            addresses.setFans((Fans) session.getAttribute("weixin"));
            if (addressesList.isEmpty()) {
                addresses.setFlag(true);
            }
            addressesDao.save(addresses);
            jsonStatus.status = 0;
            jsonStatus.text = "successful";
        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = "fail";
        }
        return gson.toJson(jsonStatus);

    }

    @RequestMapping(value = "/fans/address", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getaddress(HttpSession session) {
        JsonListBean<Addresses> jsonStatus = new JsonListBean<Addresses>();

        try {
            Fans fans = (Fans) session.getAttribute("weixin");
            jsonStatus.list = addressesDao.findByFans(fans.getId());
            jsonStatus.status = 0;
            jsonStatus.text = "successful";
        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = "fail";
        }
        return gson.toJson(jsonStatus);

    }

    @RequestMapping(value = "/fans/address/flag/{flag}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getaddressFlag(HttpSession session, @PathVariable boolean flag) {
        JsonListBean<Addresses> jsonStatus = new JsonListBean<Addresses>();

        try {
            Fans fans = (Fans) session.getAttribute("weixin");
            jsonStatus.list = addressesDao.findByFansAndflag(fans.getId(), flag);
            jsonStatus.status = 0;
            jsonStatus.text = "successful";
        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = "fail";
        }
        return gson.toJson(jsonStatus);

    }

    @RequestMapping(value = "/fans/address/status/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String changeAddressStatus(HttpSession session, @PathVariable Long id) {
        JsonStatus jsonStatus = new JsonStatus();

        try {
            Fans fans = (Fans) session.getAttribute("weixin");
            for (Addresses addresses : addressesDao.findByFansAndflag(fans.getId(), true)) {
                addressesDao.setStatus(false, addresses.getId());
            }
            addressesDao.setStatus(true, id);
            jsonStatus.status = 0;
            jsonStatus.text = "successful";
        } catch (Exception e) {
            jsonStatus.status = 1;
            jsonStatus.text = "fail";
        }
        return gson.toJson(jsonStatus);

    }

    /**
     * 展示所有热销商品
     *
     * @return
     */
    @RequestMapping(value = "/goods/hot", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String goodsAll() {
        JsonListBean<Goods> jsonListBean = new JsonListBean<Goods>();

        try {
            List<Goods> goodsJsonList;
            goodsJsonList = goodsDao.findHotGoods(true);
            jsonListBean.list = goodsJsonList;
            jsonListBean.status = 0;
            jsonListBean.text = "successful";

            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
            return gson.toJson(jsonListBean);
        }


    }

    /**
     * 展示所有精品商品
     *
     * @return
     */
    @RequestMapping(value = "/goods/best", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String goodsBest() {
        JsonListBean<Goods> jsonListBean = new JsonListBean<Goods>();

        try {
            List<Goods> goodsJsonList;
            goodsJsonList = goodsDao.findBestGoods(true);
            jsonListBean.list = goodsJsonList;
            jsonListBean.status = 0;
            jsonListBean.text = "successful";

            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";
            return gson.toJson(jsonListBean);
        }


    }

    @RequestMapping(value = "/goods/searchR", method = RequestMethod.POST)
    public String getserach(String name) {
        JsonListBean<Goods> jsonListBean = new JsonListBean<Goods>();

        try {
            List<Goods> goodsJsonList;
            goodsJsonList = goodsDao.findSearchGoods("%" + name + "%");
            jsonListBean.list = goodsJsonList;
            jsonListBean.status = 0;
            jsonListBean.text = "successful";

        } catch (Exception e) {
            jsonListBean.status = 1;
            jsonListBean.text = "fail";

        }

        return gson.toJson(jsonListBean);

    }


    @RequestMapping(value = "/zhu/addToCart", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String addCart(ServletRequest request, HttpSession session) {
        JsonStatus jsonStatus = new JsonStatus();

        try {
            Fans fans = (Fans) session.getAttribute("weixin");
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setFans_weixing(fans.getWeixing());
            shoppingCart.setQuantity(Long.decode(request.getParameter("quantity")));
            shoppingCart.setGoods(goodsDao.findOne(Long.decode(request.getParameter("goodsId"))));
            shoppingCart.setGoods_type(request.getParameter("type"));
            shoppingCartDao.save(shoppingCart);

            jsonStatus.text = "successful";
            jsonStatus.status = 0;

            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/order/purchase", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String purchase(ServletRequest request, HttpSession session) {
        JsonStatus jsonStatus = new JsonStatus();


        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowData = simpleDateFormat.format(date);
        SimpleDateFormat simpleDateFormatTrue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String trueData = simpleDateFormatTrue.format(date);
        try {
            String number = nowData + ((Fans) session.getAttribute("weixin")).getWeixing();
            Fans fans = (Fans) session.getAttribute("weixin");
            int length = Integer.decode(request.getParameter("flag"));
            for (int i = 0;i<length;i++){
                Workorder workorder = new Workorder();
                workorder.setOrderNumber(number);
                workorder.setFans(fans);
                workorder.setAddresses(addressesDao.findOne(Long.decode(request.getParameter("addressId"))));
                workorder.setNote(request.getParameter("note"));
                workorder.setOrder_status(SystemConfig.ORDER_WAIT_PAY);
                workorder.setAdd_time(trueData);
                workorder.setGoods(goodsDao.findOne(Long.decode(request.getParameter("goodsId"+i))));
                workorder.setPrice(request.getParameter("price"+i));
                workorder.setAmount(Integer.decode(request.getParameter("amount"+i)));
                workorderDao.save(workorder);
            }
            jsonStatus.text = number;
            jsonStatus.status = 0;

            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }


    @RequestMapping(value = "/order/payment/{type}/{orderId}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String payment(ServletRequest request, HttpSession session, @PathVariable int type, @PathVariable String orderId) {
        JsonStatus jsonStatus = new JsonStatus();


        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormatTrue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String trueData = simpleDateFormatTrue.format(date);
            Fans fans = (Fans) session.getAttribute("weixin");
            List<Workorder> workorderList = workorderDao.findIdByOrderNumber(orderId);
            for (Workorder workorder :workorderList){
                Goods goods = goodsDao.findOne(workorder.getGoods().getId());
                Long goodsid = goods.getId();
                Long goodsNumber = goods.getGoods_number() - workorder.getAmount();
                if (workorder.getFans().getId().equals(fans.getId())) {
                    workorder.setPay_name(type);
                    workorder.setOrder_status(SystemConfig.ORDER_WAIT_push);
                    workorder.setPay_time(trueData);
//                    goodsDao.upadateGoodsNumber(goodsNumber,goodsid);
                    workorderDao.save(workorder);
                    jsonStatus.text = "successful";
                    jsonStatus.status = 0;
                } else {
                    jsonStatus.text = "fail";
                    jsonStatus.status = 1;
                }
            }
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/order/my", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String payment(ServletRequest request, HttpSession session) {
        JsonListBean<Workorder> jsonStatus = new JsonListBean<Workorder>();
        try {
            Fans fans = (Fans) session.getAttribute("weixin");
            jsonStatus.list = workorderDao.findByFansId(fans.getId());
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/examine", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String examine() {
        JsonListBean<Users> jsonStatus = new JsonListBean<Users>();
        try {
            jsonStatus.list = usersDao.findNotPass();
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/examine/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String examinePass(@PathVariable Long id) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            usersDao.setPass(id);
            Authorities authorities = new Authorities();
            authorities.setAuthority("ROLE_SELLER");
            authorities.setUsername(usersDao.findOne(id).getUsername());
            authoritiesDao.save(authorities);
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/seller", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSeller() {
        JsonListBean<Users> jsonStatus = new JsonListBean<Users>();
        try {
            jsonStatus.list = (List<Users>) usersDao.findAll();
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/seller/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String detailseller(@PathVariable Long id) {
        JsonBean<Users> jsonBean = new JsonBean<>();
        try {
            jsonBean.bean = usersDao.findOne(id);
            jsonBean.text = "successful";
            jsonBean.status = 0;
            return gson.toJson(jsonBean);
        } catch (Exception e) {
            jsonBean.text = "fail";
            jsonBean.status = 1;
            return gson.toJson(jsonBean);
        }
    }

    @RequestMapping(value = "/mmt_admin/seller/goods/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String sellergoods(@PathVariable Long id) {
        JsonListBean<Goods> jsonStatus = new JsonListBean<>();
        try {
            jsonStatus.list = goodsDao.findBySeller(id);
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/index/{myuse}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSeller(@PathVariable String myuse) {
        JsonListBean<MyIndex> jsonStatus = new JsonListBean<MyIndex>();
        try {
            jsonStatus.list = myIndexDao.findByUserDesc(myuse);
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/index/{id}", method = RequestMethod.DELETE, produces = "text/html;charset=UTF-8")
    public String indexDelete(@PathVariable Long id) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            myIndexDao.delete(id);
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/index/{id}", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String indexPut(@PathVariable Long id, ServletRequest request) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            myIndexDao.upadateHeat(Integer.decode(request.getParameter("heat")),Long.decode(request.getParameter("goodsId")),id);
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/index/save", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String indexPut(ServletRequest request) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            MyIndex myIndex = new MyIndex();
            myIndex.setHeat(Integer.decode(request.getParameter("heat")));
            myIndex.setPurpose("hot");
            myIndex.setGoods(goodsDao.findOne(Long.decode(request.getParameter("goodsId"))));
            myIndexDao.save(myIndex);
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/indexs/{id}/{goods}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSeller(@PathVariable Long id, @PathVariable Long goods) {
        JsonStatus jsonStatus = new JsonStatus();
        try {
            myIndexDao.upadateGoodsId(goods, id);
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/mmt_admin/report/turnover/{type}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getEcharts(@PathVariable int type) {

        JsonListBean<Echarts> jsonListBean = new JsonListBean<>();
        try {
            List<Echarts> list = new ArrayList<>();
            if (type == 0) {
                list = turnoverDay(SystemConfig.Start_Day,workorderDao.findPayOrder());
            } else if (type == 1) {
                list = turnoverMonth(SystemConfig.Start_Month,workorderDao.findPayOrder());
            } else if (type == 2) {
                list = turnoverYear(SystemConfig.Start_Year,workorderDao.findPayOrder());
            }
            jsonListBean.list = list;
            jsonListBean.text = "successful";
            jsonListBean.status = 0;
            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.text = "fail";
            jsonListBean.status = 1;
            return gson.toJson(jsonListBean);
        }
    }

    /**
     * 添加一个分类
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/mmt_admin/category/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String addCategory(ServletRequest request, HttpSession session) {
        String x = request.getParameter("parentid");
        Long parentid = Long.decode(request.getParameter("parentid"));
        String name = request.getParameter("name");

        JsonBean<Category> jsonBean = new JsonBean<Category>();
        try {
            categoryDao.insertCategory(name, parentid);
            categoryDao.addCount(parentid);
            jsonBean.bean = categoryDao.findBynameAndCategory(name,parentid);
            jsonBean.status = 0;
            jsonBean.text = "successful";

        } catch (Exception e) {

            jsonBean.status = 1;
            jsonBean.text = "fail";

        }
        return gson.toJson(jsonBean);
    }

    @RequestMapping(value = "/mmt_admin/category/{id}", method = RequestMethod.DELETE, produces = "text/html;charset=UTF-8")
    public String addCategory(@PathVariable Long id) {


        JsonStatus jsonStatus = new JsonStatus();
        try {
            categoryDao.delete(id);
            jsonStatus.status = 0;
            jsonStatus.text = "successful";

        } catch (Exception e) {

            jsonStatus.status = 1;
            jsonStatus.text = "fail";

        }
        return gson.toJson(jsonStatus);
    }

    @RequestMapping(value = "/seller/goods", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getSellerGoods() {

        JsonListBean<Goods> jsonListBean = new JsonListBean<>();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {

            jsonListBean.list = goodsDao.findBySeller(usersDao.findByUsername(userDetails.getUsername()).getId());
            jsonListBean.text = "successful";
            jsonListBean.status = 0;
            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.text = "fail";
            jsonListBean.status = 1;
            return gson.toJson(jsonListBean);
        }
    }

    @RequestMapping(value = "/seller/goods/{id}", method = RequestMethod.DELETE, produces = "text/html;charset=UTF-8")
    public String deleteGoodsSeller(@PathVariable Long id) {
        JsonStatus jsonStatus = new JsonStatus();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {
            Goods goods = goodsDao.findOne(id);
            if (userDetails.getUsername().equals(goods.getUsers().getUsername())) {
                goodsDao.delete(id);
                jsonStatus.text = "successful";
                jsonStatus.status = 0;
            } else {
                jsonStatus.text = "fail";
                jsonStatus.status = 1;
            }
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/seller/goods", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String editGoodsSeller(ServletRequest request) {
        JsonStatus jsonStatus = new JsonStatus();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {
            Long id = Long.decode(request.getParameter("goodsId"));
            Goods goods = goodsDao.findOne(id);
            if (userDetails.getUsername().equals(goods.getUsers().getUsername())) {
                Long price = Long.decode(request.getParameter("price"));
                Long number = Long.decode(request.getParameter("number"));
                String name = request.getParameter("name");
                goods.setPrice(price);
                goods.setGoods_number(number);
                goods.setName(name);
                goodsDao.save(goods);
                jsonStatus.text = "successful";
                jsonStatus.status = 0;
            } else {
                jsonStatus.text = "fail";
                jsonStatus.status = 1;
            }
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/seller/order/{type}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String editGoodsSeller(@PathVariable int type) {
        JsonListBean<Workorder> workorderJsonListBean = new JsonListBean<>();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {
            Long userId = usersDao.findByUsername(userDetails.getUsername()).getId();
            workorderJsonListBean.list = workorderDao.findByOrderStatus(userId, type);
            workorderJsonListBean.text = "successful";
            workorderJsonListBean.status = 0;

            return gson.toJson(workorderJsonListBean);
        } catch (Exception e) {
            workorderJsonListBean.text = "fail";
            workorderJsonListBean.status = 1;
            return gson.toJson(workorderJsonListBean);
        }
    }

    @RequestMapping(value = "/seller/order", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String getAllOrder() {
        JsonListBean<Workorder> workorderJsonListBean = new JsonListBean<>();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {
            Long userId = usersDao.findByUsername(userDetails.getUsername()).getId();
            workorderJsonListBean.list = workorderDao.findAllGoods(userId);
            workorderJsonListBean.text = "successful";
            workorderJsonListBean.status = 0;
            return gson.toJson(workorderJsonListBean);
        } catch (Exception e) {
            workorderJsonListBean.text = "fail";
            workorderJsonListBean.status = 1;
            return gson.toJson(workorderJsonListBean);
        }
    }

    @RequestMapping(value = "/seller/deliver/{id}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String deliver(@PathVariable Long id) {
        JsonStatus jsonStatus = new JsonStatus();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {

            Workorder workorder = workorderDao.findOne(id);
            if (userDetails.getUsername().equals(workorder.getUsers().getUsername())) {
                workorder.setOrder_status(SystemConfig.ORDER_WAIT_recive);
                workorderDao.save(workorder);
                jsonStatus.text = "successful";
                jsonStatus.status = 0;
            } else {
                jsonStatus.text = "fail";
                jsonStatus.status = 1;
            }
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }

    @RequestMapping(value = "/seller", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String deliver() {
        JsonBean<Users> jsonStatus = new JsonBean<>();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {
            jsonStatus.bean = usersDao.findByUsername(userDetails.getUsername());
            jsonStatus.text = "successful";
            jsonStatus.status = 0;
            return gson.toJson(jsonStatus);
        } catch (Exception e) {
            jsonStatus.text = "fail";
            jsonStatus.status = 1;
            return gson.toJson(jsonStatus);
        }
    }


    @RequestMapping(value = "/seller/turnover/{type}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String sellerTurnover(@PathVariable int type) {

        JsonListBean<Echarts> jsonListBean = new JsonListBean<>();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  //spring security获取登陆用户信息

                .getAuthentication()

                .getPrincipal();
        try {
            String regTime = usersDao.findByUsername(userDetails.getUsername()).getRegTime();
            String year = regTime.substring(0, 3);
            String ss = regTime.substring(3, 4);
            year= year+String.valueOf(Integer.parseInt(ss)-1);
            String month = regTime.substring(0, 7);
            String day = regTime.substring(0, 10);
            List<Echarts> list = new ArrayList<>();
            if (type == 0) {
                list = turnoverDay(day,workorderDao.findPayOrder());
            } else if (type == 1) {
                list = turnoverMonth(month,workorderDao.findPayOrder());
            } else if (type == 2) {
                list = turnoverYear(year,workorderDao.findPayOrder());
            }
            jsonListBean.list = list;
            jsonListBean.text = "successful";
            jsonListBean.status = 0;
            return gson.toJson(jsonListBean);
        } catch (Exception e) {
            jsonListBean.text = "fail";
            jsonListBean.status = 1;
            return gson.toJson(jsonListBean);
        }
    }


    @RequestMapping(value = "/verify", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String verify(ServletRequest request) {
        try {
        WeixingVerify weixingVerify = new WeixingVerify();
        boolean flag = weixingVerify.check(request.getParameter("signature"),
                request.getParameter("timestamp"),
                request.getParameter("nonce"));
        if (flag){
            return request.getParameter("echostr");
        }else {
            return "false";
        }
        } catch (Exception e) {
            return "false";
        }
    }


    /**
     * 计算年 月 日 营业额
     *
     * @param list
     * @return
     */
    private List<Echarts> turnoverMonth(String began,List<Workorder> list) {
//        String began = SystemConfig.Start_Month;
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM");
        int filed = Calendar.MONTH;
        return turnData(list, began, sm, filed);
    }

    private List<Echarts> turnoverDay(String began,List<Workorder> list) {
//        String began = SystemConfig.Start_Day;
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
        int filed = Calendar.DAY_OF_MONTH;
        return turnData(list, began, sm, filed);
    }

    private List<Echarts> turnoverYear(String began,List<Workorder> list) {
//        String began = SystemConfig.Start_Year;
        SimpleDateFormat sm = new SimpleDateFormat("yyyy");
        int filed = Calendar.YEAR;
        return turnData(list, began, sm, filed);
    }

    private List<Echarts> turnData(List<Workorder> list, String began, SimpleDateFormat sm, int filed) {
        List<Echarts> echartsList = new ArrayList<>();
        String thisMonth = sm.format(new Date());
        Date date = null;
        try {
            date = sm.parse(thisMonth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cl = Calendar.getInstance();
        cl.setTime(date);
        int i = -1;
        while (!began.equals(thisMonth)) {
            Echarts echarts = new Echarts();
            echarts.data = thisMonth;
            echarts.value = 0;
            echartsList.add(echarts);
            cl.add(filed, i);
            thisMonth = sm.format(cl.getTime());

        }
        for (Workorder workorder : list) {
            int j = 0;
            for (Echarts echarts : echartsList) {
                if (workorder.getPay_time().startsWith(echarts.data)) {
                    echarts.value = echarts.value + Float.parseFloat(workorder.getPrice());
                }
                echartsList.set(j, echarts);
                j++;
            }

        }
        Collections.reverse(echartsList);
        return echartsList;
    }

    private int getRandom() {   //生成4位随机数
        int max = 9999;
        int min = 1000;
        Random random = new Random();


        return random.nextInt(max) % (max - min + 1) + min;
    }

    private Image getUploadedFileInfo(MultipartFile multipartFile) throws IOException {

        Image image = new Image();
        String s = UUID.randomUUID().toString();

//        String[] strings = name.split(".");

        s = s + "." + "jpg";

        image.setImageName(s);
        image.setImageSize(String.valueOf(multipartFile.getSize()));
        image.setImageType(multipartFile.getContentType());
        image.setUrl("/resources/image/" + s);

        return image;
    }

    private void saveFileToLocalDisk(MultipartFile multipartFile, String imageName) throws IOException,
            FileNotFoundException {

        String outputFileName = getOutputFilename(imageName);


        FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName));
    }

    private String getOutputFilename(String imageName) throws IOException {

//        System.out.println("/resources/image/" + multipartFile.getOriginalFilename());


        return servletContext.getRealPath("/resources/image/" + imageName);

    }

    private class JsonListBean<T> {
        private int status;
        private String text;
        private List<T> list;
    }

    private class JsonBean<T> {
        private int status;
        private String text;
        private T bean;
    }

    private class Echarts {
        private String data;
        private float value;
    }

    private class JsonStatus {
        private int status;
        private String text;
    }
}
